package com.usian.common.web.wemedia;

import com.alibaba.fastjson.JSON;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.threadlocal.AdminThreadLocalUtils;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * nacos 在官方让我们在  内网搭建注册中心
 * （所有微服务都在内网部署）让所有请求 都必须携带token 所有请求都需要验证token的合法
 * 使用网关统一配置 外网访问  使用HTTPS协议
 * 1. 续期   当token即将过期  需要重新生成令牌  与前端配合 替换
 * 2. 安全   检验token是否合法 合法即登录  不合法直接响应  不允许访问controller
 * 3. 自己接口访问权
 */

@Order(1)
@WebFilter(filterName = "WemediaTokenFilter",urlPatterns = "/*")
public class WemediaTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ResponseResult<?> responseResult = new ResponseResult<>();
        //放行 login
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        if(request.getRequestURI().contains("/login/in")){
            filterChain.doFilter(request,response);
            return;
        }
        // 1. 解析token
        String token =  request.getHeader("token");
        if(StringUtils.isNotEmpty(token)){
            Claims claims =  AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            if(result == 0 || result == -1){
                // 成功  设置threadLocal
                Integer id =  (Integer)claims.get("id");
                WmUser wmUser = new WmUser();
                wmUser.setId(id);
                WmThreadLocalUtils.setUser(wmUser);
                // 2. 判断是否过期
                if(result == -1){
                    response.setHeader("REFRESH_TOKEN",AppJwtUtil.getToken(Long.parseLong(wmUser.getId()+"")));
                }
                filterChain.doFilter(request,response);
                return;
            }else if(result == 1){
                responseResult = ResponseResult.setAppHttpCodeEnum(AppHttpCodeEnum.TOKEN_EXPIRE);
            } else if(result ==2){
                responseResult = ResponseResult.setAppHttpCodeEnum(AppHttpCodeEnum.TOKEN_EXPIRE);
            }
        }else{
            responseResult = ResponseResult.setAppHttpCodeEnum(AppHttpCodeEnum.TOKEN_REQUIRE);
        }
        // 类型
        response.setContentType("application/json");
        // 编码
        response.setCharacterEncoding("UTF-8");
        // 内容
        response.getOutputStream().write(JSON.toJSONString(responseResult).getBytes());
    }
}
